package cn.legym.garp.gateway.traffic.param;

import cn.legym.garp.gateway.traffic.ParamSourceParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * create by pipisun on 2021/9/6
 * copyright © 2017-2021 Legym Technology Co.,Ltd. All rights reserve
 * d.
 * file description:
 * last update by {} on {}
 * update description:
 */
@Slf4j
@Component
public class UrlParamParser implements ParamSourceParser {

    @Override
    public String parse(ServerHttpRequest request, String key) {

        String[] paramString = request.getURI().toString().split("\\?");
        if (paramString.length <= 1) {
            return null;
        }
        String upperKey = key.toUpperCase();
        List<String> results = Arrays.stream(paramString[1].split("&"))
                .filter(p -> p.toUpperCase().startsWith(upperKey))
                .map(p -> p.split("="))
                .filter(a -> a.length > 1)
                .map(a -> a[1].trim()).collect(Collectors.toList());
        if (results.isEmpty()) {
            return null;
        }
        if (results.size() > 1) {
            log.warn("multiple param found with key={} ,url={}", key, request.getURI());
        }
        return results.get(0);
    }
}
